

cd $firmpath

use $correspath/corres_nc8$firstyear$lastyear, clear
keep if year==2002
rename nc8 nc8_2002
tostring nc8_2002, replace 
replace nc8_2002="0"+ nc8_2002 if length(nc8_2002)==7 
g hs6_2002=substr(nc8_2002,1,6) 
egen count=count(id_conc), by(id_conc)
drop if count>30 // drop 2 id_conc that have more than 30 CN8 products (79 and 139 resp.) 
keep id_conc hs6 
duplicates drop id_conc hs6, force 
save temp, replace
	
use base_4decile$firstyear$lastyear$variant, clear 
sort id_conc
joinby id_conc using temp
egen hs=group(hs6_2002)
save base_4reg, replace 
erase temp.dta 


estimate_bydecile base_4reg dur $variant $product$firstyear$lastyear

collapse (mean) rs_hs6_b rs_hs6_se, by(hs6_2002) 
egen rank=rank(rs_hs6_b), f
xtile decile=rank, n(10) 
qui tab decile, g(d_) 
save $rspath/rs_hs02_$firstyear$lastyear.dta, replace